WikiParser = function(t, infobox)
{
  var self = this;
  this.text = t.replace(/('''|<ref>)([\w\s\d\W][^<>]+?)(<\/ref>|''')/g,function(m){ return self.parse(m)}).replace(/(([\{]{1,2}([\w\s\d\W][^\{\}]+?)[\}]{1,2})|([\[]{1,2}([\w\s\d\W][^\[\]]+?)[\]]{1,2}))/g, function(m){ return self.parse(m)});
  //http://en.wikipedia.org/w/index.php?title=Special:Filepath/imagename

}

WikiParser.prototype.parse = function(m)
{
  if(m.substring(0,3) == "'''") return '<b>'+m.substring(3,m.length-3)+'</b>';  
  if(m.substring(0,2) == '[[') {
    var m = m.substring(2, m.length-2);
    var propeties = m.split('|');

    //alert(propeties[0])
    if(propeties.length == 1) return '<a href="javascript:WikiSearch.ShowInfoBox(\'http://en.wikipedia.org/wiki/'+encodeURIComponent(window._ws.addslashes(propeties[0]))+'\')">'+propeties[0]+'</a>';
    else return '<a href="javascript:WikiSearch.ShowInfoBox(\'http://en.wikipedia.org/wiki/'+encodeURIComponent(window._ws.addslashes(propeties[0]))+'\')">'+propeties[1]+'</a>';
  }
  return '';
}
///////////////////////////////////////////////////////////
WikiSearch = {};
WikiSearch = function()
{
  this.url = 'http://search.yahooapis.com/WebSearchService/V1/webSearch?'+
             '&appid=WikiSearch'+
             '&site=en.wikipedia.org'+ 
             '&results=10'+
             '&output=json';
  this.wiki_url = 'http://en.wikipedia.org/w/api.php?action=query&prop=revisions|imageinfo&rvprop=content&format=json&callback=wikicb&titles=';
  this.target;
  this.ajax;
  this.r;
  this.last_info_page;

  window._ws = this;
}

WikiSearch.inherits(WebService);

WikiSearch.prototype.search = function(query)
{
  onloading(this.target);
  var params = '&query=' + encodeURIComponent(query) + '&callback=WikiSearch.CBa';
  this.JSONcall(this.url+params,'wikiSearchScript');
}

WikiSearch.CBa = function(r)
{
  if(!window._ws.r) window._ws.r = r;
  if(!r) r = window._ws.r;
  var html = '';
  
  if(r.ResultSet.Result.length)
  { 
    html += '<p>These are some Wikipedia articles you may find interesting</p>' 
    for (var i = 0; i < r.ResultSet.Result.length; i++) {
  
      html += '<p><a onclick="WikiSearch.ShowSummary(this)" href="javascript: void(0)" title="Click for summary"><b>'+r.ResultSet.Result[i].Title.split(' - ')[0]+'</b></a><span style="display:none;"><br />'+r.ResultSet.Result[i].Summary+'&nbsp;<i><a href="javascript:WikiSearch.ShowInfoBox(\''+r.ResultSet.Result[i].Url+'\')">Info</a>&nbsp;|&nbsp;<a href="'+r.ResultSet.Result[i].Url+'" target="_blank">Direct Link</i></span></p>';
    }
  }
  else html += '<strong>Sorry, nothing found</strong>';
  
  window._ws.last_info_page = null;
  window._ws.target.innerHTML = html;
}

WikiSearch.CBb = function(d)
{  
  if(!d && window._ws.last_info_page){
    var d = window._ws.last_info_page;
    window._ws.last_info_page = null;
  }
  var last = d;
  
  
  for (var i in d.query.pages) {
    if(d.query.pages.hasOwnProperty(i)) 
    {
      var stop = false;
      try { var title = d.query.pages[i].title; d = d.query.pages[i].revisions[0]['*'];  }
      catch(e) { 
      alert(e);
      stop = true; 
      break;
    }
    //try { var title = d.query.pages[i].title; d = d.query.pages[i].revisions[0].*; } 
    //catch(e2){ alert(e2); stop = true;break;}
  }
}
  if(!stop && d.indexOf('#REDIRECT')>-1){
    var url = d.substring(d.indexOf('[')+2,d.indexOf(']'));
    WikiSearch.ShowInfoBox('/'+encodeURIComponent(url));
    return;
  }
  
  window._ws.target.innerHTML = '<p>'+
  (window._ws.last_info_page ?'<a href="javascript:WikiSearch.CBb()">Back to first article</a> | ':'')
  +'<a href="javascript:WikiSearch.CBa()">Search results</a></p>';
  
  if(last && ! window._ws.last_info_page)
    window._ws.last_info_page = last;
  
  if(stop) { window._ws.target.innerHTML += '<strong>Information not available :(</strong>'; return; }
  
  //extract the infobox
  if(d.match(/(\{\{[\s\w]*infobox[\s\w\W\S][^|]*|)/i)){
    var infoStart = d.indexOf('|')+1;
    var info = false;
    var end = 1;
    var endPos = 0;
  
    if(infoStart > -1){
      for(var c=infoStart; c < (d.length-1); c++){
        if((d[c]==d[c+1]) && d[c]=='}'){
          end--;        
          if(end == 0) { info = d.substring(infoStart,c); endPos = c+2; break; }      
        }
        if((d[c]==d[c+1]) && d[c]=='{'){
          end++;      
        }
      }
      //alert(info);   
    }
  }
  var nextTopic = d.indexOf('==');
  if(nextTopic-endPos > 600 && nextTopic-endPos < 2000) var description = d.substring(endPos, nextTopic);
  else {
   var end = endPos+1+d.substring(endPos+1).indexOf("\n\n");
   end = end > 1999 ? end : end+endPos+4+d.substring(end+endPos+4).indexOf("\n\n");

   var description = d.substring(endPos,end);
   if(nextTopic>=0) description = description.replace(/==([\w\W\s][^=]+)==/g, function(m){ return '<p><b>'+m.substring(2,m.length-2)+'</b></p>'; });
  }
  var wp = new WikiParser(description);
  window._ws.target.innerHTML += wp.text+'<p style="text-align:right;"><a href="http://en.wikipedia.org/wiki/'+encodeURIComponent(title)+'" target="_blank">Read the entire article on Wikipedia</a></p>';
}

WikiSearch.ShowInfoBox = function(url)
{
  var self = window._ws;
  if(url.substring(0,1) != '/'){ //we have a full URL
    var end = url.indexOf('?');
    end = end > 0 ? end : url.length;
  }
  var title = end ? url.substring(url.indexOf('/wiki/')+6, end): url.substring(1,url.length);
  
  onloading(self.target);
  self.JSONcall(self.wiki_url+title,'w_infoBox');
}

WikiSearch.ShowSummary = function(el)
{
  var summary = el.nextSibling;
  if(summary.style.display == 'none') summary.style.display = 'inline';
  else summary.style.display = 'none';
}

function wikicb(w_data){ WikiSearch.CBb(w_data); }
